<script lang="ts" setup>
import { createCardAPI } from "@/apis/card";
import type { CardParams } from "@/types/card";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
} from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";

// 1. 添加月卡 111
// 车辆信息表单，Partial 泛型工具类转可选
const carInfoForm = reactive<Partial<CardParams>>({
  personName: "", // 车主姓名12
  phoneNumber: "", // 联系方式
  carNumber: "", // 车牌号码
  carBrand: "", // 车辆品牌
});

// 表单验证，非空和正则校验
const carInfoFormRules = reactive<FormRules<typeof carInfoForm>>({
  personName: [
    { required: true, message: "请输入车主姓名", trigger: "blur" },
    {
      // 安装插件 any-rule，选择姓名
      pattern: /^(?:[\u4e00-\u9fa5·]{2,16})$/,
      message: "车主姓名格式不正确",
      trigger: "blur",
    },
  ],
  phoneNumber: [
    { required: true, message: "请输入联系方式", trigger: "blur" },
    {
      pattern: /^1\d{10}$/,
      message: "手机号格式不正确",
      trigger: "blur",
    },
  ],
  carNumber: [
    { required: true, message: "请输入车牌号码", trigger: "blur" },
    {
      // 安装插件 any-rule，右键 -> 正则大全 -> 车牌
      pattern:
        /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/,
      message: "车牌号码格式不正确",
      trigger: "blur",
    },
  ],
  carBrand: [{ required: true, message: "请输入车辆品牌", trigger: "blur" }],
});

// 缴费信息表单
const feeForm = reactive({
  payTime: [] as string[], // 支付时间
  paymentAmount: "", // 支付金额
  paymentMethod: "", // 支付方式
});

// 缴费规则
const feeFormRules = ref({
  payTime: [
    {
      required: true,
      message: "请选择支付时间",
    },
  ],
  paymentAmount: [
    {
      required: true,
      message: "请输入支付金额",
      trigger: "blur",
    },
  ],
  paymentMethod: [
    {
      required: true,
      message: "请选择支付方式555",
      trigger: "change",
    },
  ],
});

// 支付方式列表
const payMethodList = [
  {
    value: "Alipay",
    label: "支付宝",
  },
  {
    value: "WeChat",
    label: "微信",
  },
  {
    value: "Cash",
    label: "线下",
  },
];

const carInfoFormRef = ref<FormInstance>();
const feeFormRef = ref<FormInstance>();
// 路由器 -> 用于页面跳转
const router = useRouter();
// 路由 -> 获取页面路由参数
const route = useRoute();

// 提交表单时统一校验
const onSubmit = async () => {
  try {
    // 校验两个表单是否正确
    await carInfoFormRef.value?.validate();
    await feeFormRef.value?.validate();
    // 两个表单都校验通过后，再提交表单
    await createCardAPI({
      personName: carInfoForm.personName,
      phoneNumber: carInfoForm.phoneNumber,
      carNumber: carInfoForm.carNumber,
      carBrand: carInfoForm.carBrand,
      cardStartDate: feeForm.payTime[0],
      cardEndDate: feeForm.payTime[1],
      paymentAmount: feeForm.paymentAmount,
      paymentMethod: feeForm.paymentMethod,
    } as CardParams);
    // 成功轻提示
    ElMessage({ message: "校验成功", type: "success" });
    // 提交成功，返回上一页
    router.back();
  } catch (error) {
    console.log("错误信息", error);
    // 如果是请求错误，响应拦截器已处理，所以直接 return
    if ((error as any)?.response) return;
    // 否则是表单校验未通过，错误轻提示
    ElMessage({ message: "请按要求完成表单填写", type: "error" });
  }
};

// 重置表单
const onReset = async () => {
  // 弹窗确认
  await ElMessageBox.confirm("是否重置表单？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
  // 重置表单
  carInfoFormRef.value?.resetFields();
  feeFormRef.value?.resetFields();
};

// 返回上一页
const goBack = async () => {
  // 判断对象字段是否为非空
  const isNotEmpty = Object.values(carInfoForm).some((v) => v);
  console.log("对象字段是否为非空", isNotEmpty);
  // 非空的情况下才弹窗提醒
  if (isNotEmpty) {
    // 弹窗确认
    await ElMessageBox.confirm(
      "是否返回上一页，当前表单数据不做保留？",
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
  }
  // 返回上一页
  router.back();
};
</script>

<template>
  <div class="add-card">
    <header class="add-header">
      <el-page-header
        :content="route.query.id ? '编辑月卡' : '增加月卡'"
        @back="goBack"
      />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <div class="form">
          <el-form
            label-width="100px"
            :model="carInfoForm"
            :rules="carInfoFormRules"
            ref="carInfoFormRef"
          >
            <el-form-item label="车主姓名" prop="personName">
              <el-input v-model="carInfoForm.personName" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input :maxlength="11" v-model="carInfoForm.phoneNumber" />
            </el-form-item>
            <el-form-item label="车辆号码" prop="carNumber">
              <el-input v-model="carInfoForm.carNumber" />
            </el-form-item>
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-input v-model="carInfoForm.carBrand" />
            </el-form-item>
          </el-form>
          <!-- {{ carInfoForm }} -->
        </div>
      </div>
      <div class="form-container">
        <div class="title">最新一次月卡缴费信息</div>
        <div class="form">
          <el-form
            ref="feeFormRef"
            label-width="100px"
            :model="feeForm"
            :rules="feeFormRules"
          >
            <el-form-item label="有效日期" prop="payTime">
              <el-date-picker
                v-model="feeForm.payTime"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item label="支付金额" prop="paymentAmount">
              <el-input type="number" v-model="feeForm.paymentAmount" />
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="feeForm.paymentMethod" clearable>
                <el-option
                  v-for="item in payMethodList"
                  :key="item.label"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <!-- {{ feeForm }} -->
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="onReset">重置</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<style scoped lang="scss">
.add-card {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }

    .preview {
      img {
        width: 100px;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
